clear
clear mata
clear matrix
set maxvar 10000
estimates clear


use data/constructed_data/analysisdata.dta, clear

/* rename some events because names get too long for STATA */

rename any_helpr a_h // any_helpr 
local events any_rcardiac any_rstrok any_rcancr any_rmemory any_rhosp any_disab any_health3to5
foreach event in `events'  { 
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0 
    bys hhidpn: egen firstevent = min(wave*temp)
    bys hhidpn: egen ageatevent = min(oldest_age*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Pre-event wealth categories
    egen temp1 = mean(real_hatota_pc) if eventtime<0, by(hhidpn)
    bys hhidpn: egen temp2 = min(temp1)
    gen wealthpctile_pc = 1 if temp2<medwealth
    replace wealthpctile_pc = 2 if temp2>=medwealth
    drop temp1 temp2

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    forvalues l = 1/9 {
    gen a`l' = eventtime==`l'
    }

    /* Get Couple status during event and two waves before the event */
    gen single = single_female == 1 | single_male == 1

    egen single_event = max(single*e0), by(hhidpn)

    /* mark it as 0 if it's 0 in b1 or b2 */
    egen single_b2 = max(single*b2), by(hhidpn)
    egen single_b1 = max(single*b1), by(hhidpn)
    replace single_event = 0 if single_b1 == 0 | single_b2 == 0

    replace wlthpc = wlthpc/1000
    replace incpc = incpc/1000
    replace oop = oop/1000
    rename any_disability adis
    rename any_lvtenmi any_lv10 
    rename nk_lvtenmi nk_lv10
    rename any_live_nrshm any_nh
    rename any_medicaid any_mcd
    rename any_rhomcar any_hcr
    

    //Regressions
    foreach lhs of varlist a_h {
        
        /* Low wealth only */
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if wealthpctile_pc==1, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_lw

        /* high wealth only */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if wealthpctile_pc==2, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_hw

        /* Less than 65 */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if ageatevent>=55 & ageatevent<=64, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_lt65

        /* Greater than (or equal to) 65 */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if ageatevent>=65 & ageatevent<=74, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_gt65

        /* Single HHs */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if single_event == 1, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_s

        /* Non-single HHs */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if single_event == 0, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_cpl
    }

    restore
}

/* Run regression by kgender */
use data/constructed_data/kid_wave_all.dta if oldest_age>=50 & oldest_age<=85 & wave>=2, clear
local events any_rcardiac any_rstrok any_rcancr any_rmemory any_rhosp any_disab any_health3to5
//Set Panel
xtset kidid_group wave
tab wave

//Prepare variables
// Helping
gen khlp = cond(khelpr == 1, 1, 0)
replace khlp = . if khelpr == . // .z means not in helper file (so not helper) but . means no response

//Wealth Shocks
gen wpos = (real_hatota > 1.5*l.real_hatota) & l.real_hatota>20000 & l.real_hatota!=.
gen wneg = (real_hatota < .75*l.real_hatota) & l.real_hatota>20000 & l.real_hatota!=.

gen wneg2 = wneg
replace wneg2 = 0 if l.wpos==1
replace wneg2 = 0 if l2.wpos==1

//Life Expectancy
replace rliv75 = rliv85 if rliv75==.
replace rliv75 = rliv10 if rliv75==.

//Age and Race
egen ageXwave = group(oldest_age wave)
gen oldest_age2 = oldest_age^2
drop if any_nonwhite==. 

// Weight
bysort hhidpn: egen weight = mean(rwthh)

/* rename some long names */
rename any_real_ktcamt at_pk // any transfer parent -> kid 
rename any_real_kfcamt at_kp // any transfer kid -> parent
rename any_rwidowed any_rw // any parent death?

/* see above rename block for these definitions */
foreach event in `events' {
    di "`event'"
    preserve
    xtset kidid_group wave
    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 
    bys kidid_group: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    forvalues l = 1/9 {
    gen a`l' = eventtime==`l'
    }

    //Regressions - Helper stratify by kid gender (alternative is to interact and plot the interaction)

	foreach lhs of varlist khlp {
		di "`lhs'"
		/* Female kids kgender == 2 */
		xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if kgender == 2, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'_fkids

		/* Male kids kgender == 1 */
		xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if kgender == 1, fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
		eststo p`lhs'_`event'_mkids
        
	} // end main lhs loop

	restore
} // end event loop

cap drop e0 a1
gen e0 = .
gen a1 = .
label var e0 "Event Wave"
label var a1 "One Wave After"

/* Create table snippets for table C8 and C9*/
/* Create panels separated by event  */
loc NOMEAN_estout "cells(b(fmt(3) star) se(par fmt(3))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 
loc NOMEAN2_estout "stats( Observations Households, fmt(0 0)) cells(b(fmt(3) star) se(par fmt(3))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 
loc Mech_estout "cells(b(fmt(2) star) se(par fmt(2))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 
/* Create table snippets */
foreach lhs in a_h  {
    foreach event in any_rhosp any_disab any_health3to5{
        estout pkhlp_`event'_fkids pkhlp_`event'_mkids p`lhs'_`event'_s p`lhs'_`event'_cpl p`lhs'_`event'_lt65 p`lhs'_`event'_gt65 p`lhs'_`event'_lw p`lhs'_`event'_hw ///  
        using output/tablec8/`lhs'_post_`event'.tex, `NOMEAN2_estout' keep(e0 a1)
        filefilter output/tablec8/`lhs'_post_`event'.tex output/tablec8/`lhs'_post2_`event'.tex, from("Observations") to ("\BShline Observations") replace
    }   
}

foreach lhs in a_h  {
    foreach event in any_rcardiac any_rstrok any_rcancr any_rmemory{
        estout pkhlp_`event'_fkids pkhlp_`event'_mkids p`lhs'_`event'_s p`lhs'_`event'_cpl p`lhs'_`event'_lt65 p`lhs'_`event'_gt65 p`lhs'_`event'_lw p`lhs'_`event'_hw ///  
        using output/tablec9/`lhs'_post_`event'.tex, `NOMEAN2_estout' keep(e0 a1)
        filefilter output/tablec9/`lhs'_post_`event'.tex output/tablec9/`lhs'_post2_`event'.tex, from("Observations") to ("\BShline Observations") replace
    }   
}